package com.puboot.common.intercepter;

import com.puboot.module.blog.model.Customer;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Component
@AllArgsConstructor
@Slf4j
public class CustomerSessionInterceptor implements HandlerInterceptor {

    public static List<String> authList = new ArrayList<>();

    static {
        authList.add("/blog/eghg/api/eghgone");
        authList.add("/blog/eghg/api/eghgtwo");
        authList.add("/blog/eghg/api/eghgThree");
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI();
        if (authList.contains(url)) {
            if (isAjaxRequest(request)) {
                Customer customer = (Customer) request.getSession().getAttribute("customer");
                if (customer == null) {
                    String message = "登录失效";
                    response.setStatus(HttpStatus.SC_FORBIDDEN);
                    String resultData = "{\"status\":\"403\",\"msg\":\"" + message + "\"}";
                    response.getWriter().write(resultData);
                    return false;
                }
            }
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    /**
     * 判断是否是ajax请求
     *
     * @param request
     * @return
     */
    private boolean isAjaxRequest(HttpServletRequest request) {
        String header = request.getHeader("X-Requested-With");
        if (header != null && "XMLHttpRequest".equals(header)) {
            return true;
        } else {
            return false;
        }
    }
}
